<template>
  <div>
    <a-modal
      :title="title"
      :width="1200"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :footer="null"
      @cancel="handleCancel"
      :destroyOnClose="true"
    >
      <a-spin :spinning="confirmLoading">
        <!-- 基本信息 -->
        <a-card title="基本信息" :bordered="false" style="margin-bottom: 20px">
          <a-descriptions :column="3" bordered>
            <a-descriptions-item label="订单编号">{{ model.orderNo || '-' }}</a-descriptions-item>
            <a-descriptions-item label="客户名称">{{ model.customerName || '-' }}</a-descriptions-item>
            <a-descriptions-item label="工程名称" :span="2">{{ model.projectName || '-' }}</a-descriptions-item>
            <a-descriptions-item label="订单状态">
              <a-tag :color="getStatusColor(model.status)">{{ getOrderStatusText(model.status) }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="订单日期">{{ model.orderDate || '-' }}</a-descriptions-item>
            <a-descriptions-item label="交付日期">{{ model.deliveryDate || '-' }}</a-descriptions-item>
            <a-descriptions-item label="优化软件类型">
              <a-tag v-if="model.optimizationSoftwareType == 0" color="blue">长风优化软件</a-tag>
              <a-tag v-else-if="model.optimizationSoftwareType == 1" color="purple">新格尔优化软件</a-tag>
              <a-tag v-else>未知类型</a-tag>
            </a-descriptions-item>
            <a-descriptions-item v-if="model.optimizationSoftwareType !== 0" label="汇总单">
              <a-tag v-if="model.hasSummaryFile" color="green">已上传</a-tag>
              <a-tag v-else color="red">未上传</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="优化单">
              <a-tag v-if="model.hasOptimizationFile" color="green">已上传</a-tag>
              <a-tag v-else color="red">未上传</a-tag>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 订单明细 -->
        <a-card title="订单明细" :bordered="false">
          <a-tabs defaultActiveKey="1">
            <a-tab-pane key="1" tab="订单明细">
              <a-table
                size="middle"
                bordered
                :rowKey="(record) => record.id || record.windowNo"
                :columns="columns"
                :dataSource="model.detailList || []"
                :pagination="{
                  pageSize: 5,
                  showSizeChanger: true,
                  pageSizeOptions: ['5', '10', '20'],
                  showTotal: (total) => `共 ${total} 条`,
                }"
                :scroll="{ x: 1300 }"
              >
                <template slot="photoUrlSlot" slot-scope="text, record">
                  <div v-if="text" class="drawing-thumbnail-container" @click="previewDrawing(text, record)">
                    <img
                      v-if="isImageFile(text)"
                      :src="getFullImageUrl(text)"
                      class="drawing-thumbnail"
                      alt="图纸缩略图"
                      @error="handleImageError"
                    />
                    <a-icon v-else type="file-pdf" class="file-icon" />
                    <div class="thumbnail-filename">{{ getFileName(text) }}</div>
                  </div>
                  <span v-else>无图纸</span>
                </template>
                <template slot="detailOperation" slot-scope="text, record">
                  <a-button type="link" size="small" @click="handleViewDetailInfo(record)" v-if="record.id"
                    >详情</a-button
                  >
                </template>
              </a-table>
            </a-tab-pane>

            <!-- 新格尔优化软件型材清单 -->
            <a-tab-pane key="2" tab="型材清单" v-if="model.optimizationSoftwareType == 1">
              <a-table
                size="middle"
                bordered
                rowKey="id"
                :columns="profileMaterialColumns"
                :dataSource="profileMaterials"
                :pagination="{ pageSize: 10 }"
                :scroll="{ y: 300 }"
              >
                <template slot="action" slot-scope="text, record">
                  <a @click="showCutDetails(record)"> <a-icon type="eye" /> 切割方案 </a>
                </template>
              </a-table>
            </a-tab-pane>

            <!-- 长风优化软件型材清单 -->
            <a-tab-pane key="2" tab="型材清单" v-else>
              <a-table
                size="middle"
                bordered
                rowKey="id"
                :columns="cfMaterialColumns || profileMaterialColumns"
                :dataSource="profileMaterials"
                :pagination="{ pageSize: 10 }"
                :scroll="{ y: 300 }"
              >
                <template slot="action" slot-scope="text, record">
                  <a @click="showCfCutDetails(record)"> <a-icon type="eye" /> 切割详情 </a>
                </template>
              </a-table>
            </a-tab-pane>

            <!-- 新格尔优化软件配件清单 -->
            <a-tab-pane key="3" tab="配件清单" v-if="model.optimizationSoftwareType == 1">
              <a-table
                size="middle"
                bordered
                rowKey="id"
                :columns="accessoryListColumns"
                :dataSource="accessoryList"
                :pagination="{ pageSize: 10 }"
                :scroll="{ y: 300 }"
              >
              </a-table>
            </a-tab-pane>

            <!-- 长风优化软件配件清单 -->
            <a-tab-pane key="3" tab="配件清单" v-else>
              <a-table
                size="middle"
                bordered
                rowKey="id"
                :columns="cfAccessoryListColumns || accessoryListColumns"
                :dataSource="accessoryList"
                :pagination="{ pageSize: 10 }"
                :scroll="{ y: 300 }"
              >
              </a-table>
            </a-tab-pane>
          </a-tabs>
        </a-card>
        <!-- 底部按钮 -->
        <div style="text-align: center; margin-top: 20px">
          <a-button @click="handleCancel">关闭</a-button>
        </div>
      </a-spin>
    </a-modal>

    <!-- 图纸预览模态框 -->
    <a-modal
      :title="`图纸预览 - ${currentWindowNo}`"
      :visible="drawingPreviewVisible"
      @cancel="closeDrawingPreview"
      :footer="null"
      :width="1000"
      :destroyOnClose="true"
      :class="'jee-outer-modal'"
    >
      <div class="drawing-preview-container">
        <!-- 图片文件直接显示 -->
        <img
          v-if="isImageFile(currentDrawingUrl)"
          :src="currentDrawingUrl"
          class="drawing-preview-image"
          @error="handleImageError"
        />
        <!-- 非图片文件使用iframe嵌入显示 -->
        <iframe
          v-else
          :src="getPreviewUrl(currentDrawingUrl)"
          class="drawing-preview-iframe"
          frameborder="0"
          allowfullscreen
        ></iframe>
      </div>
      <div class="drawing-preview-filename">
        {{ getFileName(currentDrawingUrl) }}
      </div>
    </a-modal>

    <!-- 产品详情信息弹窗 -->
    <a-modal
      title="产品详细信息"
      :visible="detailInfoVisible"
      @cancel="handleDetailInfoCancel"
      :footer="null"
      :width="900"
      :destroyOnClose="true"
      :class="'jee-outer-modal'"
    >
      <a-spin :spinning="detailInfoLoading">
        <a-tabs defaultActiveKey="1">
          <a-tab-pane key="1" tab="配件信息">
            <a-table
              :columns="isChangfengType ? accessoriesColumnsCf : accessoriesColumnsXge"
              :dataSource="accessoriesList"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
              size="middle"
              :scroll="{ x: 'max-content' }"
              style="width: 100%"
            ></a-table>
          </a-tab-pane>
          <a-tab-pane key="2" tab="玻璃尺寸">
            <a-table
              :columns="isChangfengType ? glassSizeColumnsCf : glassSizeColumnsXge"
              :dataSource="glassSizeList"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
              size="middle"
              :scroll="{ x: 'max-content' }"
              style="width: 100%"
            ></a-table>
          </a-tab-pane>
          <a-tab-pane key="3" tab="型材尺寸">
            <a-table
              :columns="isChangfengType ? profileSizeColumnsCf : profileSizeColumnsXge"
              :dataSource="profileSizeList"
              :pagination="false"
              :rowKey="(record) => record.id || record.serialNo"
              bordered
              size="middle"
              :scroll="{ x: 'max-content' }"
              style="width: 100%"
            ></a-table>
          </a-tab-pane>
        </a-tabs>
      </a-spin>
    </a-modal>

    <!-- 切割方案详情模态框 -->
    <a-modal
      title="切割方案详情"
      :width="900"
      :visible="cutDetailsVisible"
      :footer="null"
      @cancel="() => (cutDetailsVisible = false)"
      :destroyOnClose="true"
      :class="'jee-outer-modal'"
    >
      <a-spin :spinning="detailsLoading">
        <div class="cut-details-header">
          <p><strong>型材编号：</strong>{{ currentProfileMaterial ? currentProfileMaterial.profileCode : '' }}</p>
          <p><strong>型材名称：</strong>{{ currentProfileMaterial ? currentProfileMaterial.profileName : '' }}</p>
          <p><strong>颜色：</strong>{{ currentProfileMaterial ? currentProfileMaterial.color : '' }}</p>
        </div>

        <a-table
          size="middle"
          bordered
          rowKey="id"
          :columns="cutDetailsColumns"
          :dataSource="cutDetails"
          :pagination="{ pageSize: 10 }"
        >
          <!-- 切割方案列 -->
          <template slot="cutSchemeSlot" slot-scope="text">
            <div style="word-break: break-all; white-space: pre-line">{{ text }}</div>
          </template>

          <!-- 优化率列 -->
          <template slot="optimizationRateSlot" slot-scope="text">
            {{ text ? (text * 100).toFixed(2) + '%' : '' }}
          </template>
        </a-table>
      </a-spin>
    </a-modal>

    <!-- 长风切割详情模态框 -->
    <a-modal
      title="长风切割详情"
      :width="900"
      :visible="cfCutDetailsVisible"
      :footer="null"
      @cancel="() => (cfCutDetailsVisible = false)"
      :destroyOnClose="true"
      :class="'jee-outer-modal'"
    >
      <a-spin :spinning="detailsLoading">
        <div class="cut-details-header">
          <p><strong>型材编号：</strong>{{ currentProfileMaterial ? currentProfileMaterial.profileCode : '' }}</p>
          <p><strong>型材名称：</strong>{{ currentProfileMaterial ? currentProfileMaterial.profileName : '' }}</p>
          <p><strong>颜色：</strong>{{ currentProfileMaterial ? currentProfileMaterial.color : '' }}</p>
        </div>

        <a-table
          size="middle"
          bordered
          rowKey="id"
          :columns="cfCutDetailsColumns"
          :dataSource="cfCutDetails"
          :pagination="{ pageSize: 10 }"
        >
          <!-- 切割方案列 -->
          <template slot="cutSchemeSlot" slot-scope="text">
            <div style="word-break: break-all; white-space: pre-line">{{ text }}</div>
          </template>

          <!-- 操作列 -->
          <template slot="actionSlot" slot-scope="text, record">
            <a @click="showWorkDetails(record)"><a-icon type="tool" /> 加工方案</a>
          </template>
        </a-table>
      </a-spin>
    </a-modal>

    <!-- 加工方案详情模态框 -->
    <a-modal
      title="加工方案详情"
      :width="900"
      :visible="workDetailsVisible"
      :footer="null"
      @cancel="() => (workDetailsVisible = false)"
      :destroyOnClose="true"
      :class="'jee-outer-modal'"
    >
      <a-spin :spinning="workDetailsLoading">
        <div class="cut-details-header">
          <p><strong>编码：</strong>{{ currentCutDetail ? currentCutDetail.barCode : '' }}</p>
          <p><strong>长度：</strong>{{ currentCutDetail ? currentCutDetail.length + 'mm' : '' }}</p>
          <p><strong>窗号：</strong>{{ currentCutDetail ? currentCutDetail.windowNo : '' }}</p>
        </div>

        <a-table
          size="middle"
          bordered
          rowKey="id"
          :columns="workDetailsColumns"
          :dataSource="workDetails"
          :pagination="{ pageSize: 10 }"
        >
        </a-table>
      </a-spin>
    </a-modal>
  </div>
</template>

<script>
import { getDesignOrderDetail, getOrderMaterialsAndAccessories, getCutDetails } from '@/api/oms/designFile'
import { getDictItems } from '@/api/system/dict'
import { getAction } from '@/api/manage'
import { axios } from '@/utils/request'

export default {
  name: 'DesignOrderDetail',
  data() {
    return {
      title: '订单详情',
      visible: false,
      confirmLoading: false,
      model: {},
      orderStatusDict: [], // 订单状态字典
      drawingPreviewVisible: false,
      currentDrawingUrl: '',
      currentWindowNo: '',
      $http: axios,
      columns: [
        {
          title: '窗号',
          dataIndex: 'windowNo',
          align: 'center',
          width: 80,
        },
        {
          title: '系列',
          dataIndex: 'windowSeries',
          align: 'center',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'windowColor',
          align: 'center',
          width: 120,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          align: 'center',
          width: 80,
        },
        {
          title: '总面积(㎡)',
          dataIndex: 'totalArea',
          align: 'center',
          width: 100,
        },
        {
          title: '图纸',
          dataIndex: 'photoUrl',
          align: 'center',
          width: 120,
          scopedSlots: { customRender: 'photoUrlSlot' },
        },
        {
          title: '操作',
          key: 'action',
          align: 'center',
          width: 50,
          scopedSlots: { customRender: 'detailOperation' },
        },
      ],
      // 产品详情弹窗相关
      detailInfoVisible: false,
      detailInfoLoading: false,
      currentDetailRecord: null,
      accessoriesList: [],
      glassSizeList: [],
      profileSizeList: [],

      // 型材清单相关
      profileMaterials: [],
      profileMaterialColumns: [
        {
          title: '型材编号',
          dataIndex: 'profileCode',
          width: 120,
        },
        {
          title: '型材名称',
          dataIndex: 'profileName',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 100,
        },
        {
          title: '长度(mm)',
          dataIndex: 'length',
          width: 100,
        },
        {
          title: '数量(根)',
          dataIndex: 'quantity',
          width: 100,
        },
        {
          title: '重量(kg)',
          dataIndex: 'weight',
          width: 100,
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ],

      // 配件清单相关
      accessoryList: [],
      accessoryListColumns: [
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 100,
        },
        {
          title: '配件编号',
          dataIndex: 'accessoryCode',
          width: 120,
        },
        {
          title: '配件名称',
          dataIndex: 'accessoryName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '长度/数量',
          dataIndex: 'lengthQuantity',
          width: 80,
        },
      ],

      // 切割方案详情相关
      cutDetailsVisible: false,
      detailsLoading: false,
      currentProfileMaterial: null,
      cutDetails: [],
      cutDetailsColumns: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 80,
        },
        {
          title: '长度(mm)',
          dataIndex: 'length',
          width: 100,
        },
        {
          title: '数量(根)',
          dataIndex: 'quantity',
          width: 100,
        },
        {
          title: '切割方案',
          dataIndex: 'cutScheme',
          scopedSlots: { customRender: 'cutSchemeSlot' },
        },
        {
          title: '锯向',
          dataIndex: 'cutDirection',
          width: 100,
        },
        {
          title: '优化率',
          dataIndex: 'optimizationRate',
          width: 100,
          scopedSlots: { customRender: 'optimizationRateSlot' },
        },
        {
          title: '余料(mm)',
          dataIndex: 'remnant',
          width: 100,
        },
      ],

      // 长风系统配件列定义
      accessoriesColumnsCf: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '配件名称',
          dataIndex: 'accessoryName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 80,
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 60,
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          width: 80,
        },
      ],

      // 新格尔系统配件列定义
      accessoriesColumnsXge: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 80,
        },
        {
          title: '配件编号',
          dataIndex: 'accessoryCode',
          width: 100,
        },
        {
          title: '配件名称',
          dataIndex: 'accessoryName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 80,
        },
        {
          title: '长度/数量',
          dataIndex: 'lengthQuantity',
          width: 100,
        },
      ],

      // 长风系统玻璃尺寸列定义
      glassSizeColumnsCf: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '玻璃宽',
          dataIndex: 'glassWidth',
          width: 80,
        },
        {
          title: '玻璃高',
          dataIndex: 'glassHeight',
          width: 80,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 60,
        },
        {
          title: '玻璃种类',
          dataIndex: 'glassType',
          width: 120,
        },
      ],

      // 新格尔系统玻璃尺寸列定义
      glassSizeColumnsXge: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 80,
        },
        {
          title: '玻璃名称',
          dataIndex: 'glassName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 100,
        },
        {
          title: '安装位置',
          dataIndex: 'installPosition',
          width: 100,
        },
        {
          title: '磨',
          dataIndex: 'frosted',
          width: 60,
        },
        {
          title: '宽',
          dataIndex: 'glassWidth',
          width: 80,
        },
        {
          title: '高',
          dataIndex: 'glassHeight',
          width: 80,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 60,
        },
      ],

      // 长风系统型材尺寸列定义
      profileSizeColumnsCf: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '型材名称',
          dataIndex: 'profileName',
          width: 120,
        },
        {
          title: '型材代码',
          dataIndex: 'profileCode',
          width: 100,
        },
        {
          title: '长度',
          dataIndex: 'length',
          width: 80,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 60,
        },
        {
          title: '类别',
          dataIndex: 'category',
          width: 80,
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
      ],

      // 新格尔系统型材尺寸列定义
      profileSizeColumnsXge: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 80,
        },
        {
          title: '型材编号',
          dataIndex: 'profileCode',
          width: 100,
        },
        {
          title: '型材名称',
          dataIndex: 'profileName',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 80,
        },
        {
          title: '切角',
          dataIndex: 'cutAngle',
          width: 80,
        },
        {
          title: '长度',
          dataIndex: 'length',
          width: 80,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 60,
        },
      ],

      // 长风切割详情相关
      cfCutDetailsVisible: false,
      cfCutDetails: [],
      cfCutDetailsColumns: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 80,
        },
        {
          title: '切割长度(mm)',
          dataIndex: 'length',
          width: 100,
        },
        {
          title: '编码',
          dataIndex: 'barCode',
          width: 120,
        },
        {
          title: '位置',
          dataIndex: 'position',
          width: 100,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 100,
        },
        {
          title: '切割方案',
          dataIndex: 'cutScheme',
          scopedSlots: { customRender: 'cutSchemeSlot' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'actionSlot' },
        },
      ],

      // 长风型材列定义
      cfMaterialColumns: [
        {
          title: '型材编号',
          dataIndex: 'profileCode',
          width: 120,
        },
        {
          title: '型材名称',
          dataIndex: 'profileName',
          width: 120,
        },
        {
          title: '颜色',
          dataIndex: 'color',
          width: 100,
        },
        {
          title: '长度(mm)',
          dataIndex: 'length',
          width: 100,
        },
        {
          title: '宽度(mm)',
          dataIndex: 'width',
          width: 100,
        },
        {
          title: '高度(mm)',
          dataIndex: 'height',
          width: 100,
        },
        {
          title: '数量(根)',
          dataIndex: 'quantity',
          width: 100,
        },
        {
          title: '重量(kg)',
          dataIndex: 'weight',
          width: 100,
        },
        {
          title: '备注',
          dataIndex: 'remark',
        },
        {
          title: '操作',
          dataIndex: 'action',
          width: 100,
          scopedSlots: { customRender: 'action' },
        },
      ],

      // 长风配件列定义
      cfAccessoryListColumns: [
        {
          title: '配件编号',
          dataIndex: 'accessoryCode',
          width: 120,
        },
        {
          title: '配件名称',
          dataIndex: 'accessoryName',
          width: 120,
        },
        {
          title: '规格',
          dataIndex: 'specification',
          width: 120,
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: 80,
        },
        {
          title: '单位',
          dataIndex: 'unit',
          width: 80,
        },
        {
          title: '品牌',
          dataIndex: 'brand',
          width: 80,
        },
      ],

      url: {
        loadAccessories: '/oms/cfAccessoriesTable/listByDetailIdAndType',
        loadGlassSize: '/oms/cfGlassSizeTable/listByDetailIdAndType',
        loadProfileSize: '/oms/cfProfileSizeTable/listByDetailIdAndType',
        // 切割方案详情
        getCutDetails: '/oms/designOrderProduct/getCutDetails',
      },

      // 新增的workDetails相关
      workDetailsVisible: false,
      workDetailsLoading: false,
      currentCutDetail: null,
      workDetails: [],
      workDetailsColumns: [
        {
          title: '序号',
          dataIndex: 'serialNo',
          width: 60,
        },
        {
          title: '加工名称',
          dataIndex: 'workName',
          width: 120,
        },
        {
          title: '位置',
          dataIndex: 'position',
          width: 180,
        },
        {
          title: '窗号',
          dataIndex: 'windowNo',
          width: 80,
        },
        {
          title: '编码',
          dataIndex: 'barCode',
          width: 120,
        },
      ],
    }
  },
  computed: {
    /**
     * 判断是否为长风优化软件类型
     * 0或null为长风，1为新格尔
     */
    isChangfengType() {
      console.log(this.currentDetailRecord)
      // 先检查当前查看的详情记录
      if (this.currentDetailRecord && this.currentDetailRecord.optimizationSoftwareType !== undefined) {
        return (
          this.currentDetailRecord.optimizationSoftwareType == '0' ||
          this.currentDetailRecord.optimizationSoftwareType == 0
        )
      }
      // 如果没有详情记录，则检查主表记录
      return this.model && (this.model.optimizationSoftwareType == '0' || this.model.optimizationSoftwareType == 0)
    },
  },
  created() {
    // 获取订单状态字典
    this.loadOrderStatusDict()
  },
  methods: {
    show(id) {
      this.visible = true
      this.loadData(id)
    },
    loadData(id) {
      this.confirmLoading = true
      getDesignOrderDetail(id)
        .then((res) => {
          if (res.success) {
            this.model = res.result || {}
            this.model.id = id
            // 获取完订单详情后，加载型材清单和配件清单
            this.loadMaterialsAndAccessories()
          } else {
            this.$message.warning(res.message)
          }
          this.confirmLoading = false
        })
        .catch(() => {
          this.confirmLoading = false
        })
    },
    loadOrderStatusDict() {
      getDictItems('order_status').then((res) => {
        if (res.success) {
          this.orderStatusDict = res.result || []
        }
      })
    },
    getOrderStatusText(status) {
      if (!status && status !== 0) return '未知状态'
      const found = this.orderStatusDict.find((item) => item.value == status.toString())
      return found ? found.text : '未知状态'
    },
    getStatusColor(status) {
      if (!status && status !== 0) return 'default'
      switch (parseInt(status)) {
        case 0:
          return 'orange' // 待审核
        case 1:
          return 'blue' // 审核通过
        case 2:
          return 'cyan' // 已上传汇总单
        case 3:
          return 'green' // 已上传优化单
        case 4:
          return 'purple' // 待下发
        case 5:
          return 'magenta' // 领料单待审核
        case 6:
          return 'geekblue' // 待领料
        case 7:
          return 'volcano' // 生产中
        case 8:
          return 'gold' // 已完成
        case 9:
          return 'red' // 已驳回
        default:
          return 'default'
      }
    },
    handleCancel() {
      this.visible = false
    },
    isImageFile(url) {
      if (!url) return false
      return /\.(jpg|jpeg|png|gif|bmp)$/i.test(url)
    },
    getFullImageUrl(url) {
      if (!url) return ''
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url
      }
      if (url.startsWith('windowImages/')) {
        return window._CONFIG['domianURL'] + '/sys/common/static/' + url
      }
      return window._CONFIG['domianURL'] + url
    },
    getFileName(url) {
      if (!url) return ''
      return url.split('/').pop()
    },
    handleImageError(e) {
      e.target.src = require('@/assets/nodata.png')
    },
    previewDrawing(url, record) {
      this.currentDrawingUrl = this.getFullImageUrl(url)
      this.currentWindowNo = record.windowNo || ''
      this.drawingPreviewVisible = true
    },
    closeDrawingPreview() {
      this.drawingPreviewVisible = false
      this.currentDrawingUrl = ''
      this.currentWindowNo = ''
    },
    getPreviewUrl(url) {
      // 如果是PDF文件，使用PDF预览
      if (/\.pdf$/i.test(url)) {
        return window._CONFIG['pdfViewerURL'] + encodeURIComponent(this.getFullImageUrl(url))
      }
      return this.getFullImageUrl(url)
    },
    // 获取父级Modal元素，用于解决日期选择器和下拉框被遮挡的问题
    getParentModal() {
      return document.querySelector('.jee-outer-modal')
    },
    handleViewDetailInfo(record) {
      if (!record || !record.id) {
        this.$message.warning('产品数据不完整，无法查看详情')
        return
      }

      // 保存当前查看的详情记录
      this.currentDetailRecord = record

      // 获取优化软件类型
      const optimizationSoftwareType =
        record.optimizationSoftwareType ||
        (this.model && this.model.optimizationSoftwareType ? this.model.optimizationSoftwareType : null)

      // 设置详情记录的优化软件类型，确保计算属性能正确获取
      this.currentDetailRecord.optimizationSoftwareType = optimizationSoftwareType

      console.log('当前优化软件类型........................:', optimizationSoftwareType)
      console.log('当前查看的产品........................:', record)

      // 显示详情信息模态框并设置加载状态
      this.detailInfoVisible = true
      this.detailInfoLoading = true

      // 并行加载三种数据
      const detailId = record.id
      const windowNo = record.windowNo || ''
      Promise.all([
        this.loadAccessoriesData(detailId, windowNo),
        this.loadGlassSizeData(detailId, windowNo),
        this.loadProfileSizeData(detailId, windowNo),
      ])
        .then(() => {
          // 所有数据加载完成后，关闭加载状态
          this.detailInfoLoading = false
        })
        .catch((error) => {
          console.error('加载产品详情数据失败:', error)
          this.$message.error('加载产品详情数据失败')
          this.detailInfoLoading = false
        })
    },
    handleDetailInfoCancel() {
      this.detailInfoVisible = false
      this.detailInfoLoading = false
      this.currentDetailRecord = null
      this.accessoriesList = []
      this.glassSizeList = []
      this.profileSizeList = []
    },
    // 加载配件数据
    loadAccessoriesData(detailId, windowNo) {
      return new Promise((resolve, reject) => {
        if (!detailId) {
          this.accessoriesList = []
          resolve()
          return
        }

        const apiUrl = this.isChangfengType ? this.url.loadAccessories : this.url.loadAccessories
        const params = {
          detailId: detailId,
          softwareType: this.isChangfengType ? '0' : '1',
          windowNo: windowNo || '',
        }

        getAction(apiUrl, params)
          .then((res) => {
            if (res.success) {
              if (this.isChangfengType) {
                // 长风类型，需要合并相同配件
                const accessoriesMap = new Map()
                const originalAccessories = res.result || []

                // 遍历原始配件数据
                originalAccessories.forEach((item, index) => {
                  // 生成唯一键：配件编号_配件名称_规格
                  const key = `${item.accessoryCode || ''}_${item.accessoryName || ''}_${item.specification || ''}`

                  if (accessoriesMap.has(key)) {
                    // 如果已存在相同配件，则累加数量
                    const existingItem = accessoriesMap.get(key)
                    existingItem.quantity = (parseFloat(existingItem.quantity) || 0) + (parseFloat(item.quantity) || 0)
                  } else {
                    // 如果不存在，则添加新条目并添加序号
                    item.serialNo = index + 1
                    accessoriesMap.set(key, { ...item })
                  }
                })

                // 转换回数组并重新编号
                this.accessoriesList = Array.from(accessoriesMap.values()).map((item, index) => {
                  return { ...item, serialNo: index + 1 }
                })
                console.log('汇总后的长风配件清单:', this.accessoriesList)
              } else {
                // 新格尔类型，直接使用原始数据，但需要添加序号
                this.accessoriesList = (res.result || []).map((item, index) => {
                  return { ...item, serialNo: index + 1 }
                })
              }
              resolve()
            } else {
              this.$message.warning('获取配件信息失败: ' + (res.message || '未知错误'))
              this.accessoriesList = []
              resolve() // 即使失败也继续执行
            }
          })
          .catch((err) => {
            console.error('获取配件信息异常:', err)
            this.accessoriesList = []
            resolve() // 即使失败也继续执行
          })
      })
    },

    // 加载玻璃尺寸数据
    loadGlassSizeData(detailId, windowNo) {
      return new Promise((resolve, reject) => {
        if (!detailId) {
          this.glassSizeList = []
          resolve()
          return
        }

        const apiUrl = this.isChangfengType ? this.url.loadGlassSize : this.url.loadGlassSize
        const params = {
          detailId: detailId,
          softwareType: this.isChangfengType ? '0' : '1',
          windowNo: windowNo || '',
        }

        getAction(apiUrl, params)
          .then((res) => {
            if (res.success) {
              this.glassSizeList = res.result || []
              resolve()
            } else {
              this.$message.warning('获取玻璃尺寸信息失败: ' + (res.message || '未知错误'))
              this.glassSizeList = []
              resolve() // 即使失败也继续执行
            }
          })
          .catch((err) => {
            console.error('获取玻璃尺寸信息异常:', err)
            this.glassSizeList = []
            resolve() // 即使失败也继续执行
          })
      })
    },

    // 加载型材尺寸数据
    loadProfileSizeData(detailId, windowNo) {
      return new Promise((resolve, reject) => {
        if (!detailId) {
          this.profileSizeList = []
          resolve()
          return
        }

        const apiUrl = this.isChangfengType ? this.url.loadProfileSize : this.url.loadProfileSize
        const params = {
          detailId: detailId,
          softwareType: this.isChangfengType ? '0' : '1',
          windowNo: windowNo || '',
        }

        getAction(apiUrl, params)
          .then((res) => {
            if (res.success) {
              this.profileSizeList = res.result || []
              resolve()
            } else {
              this.$message.warning('获取型材尺寸信息失败: ' + (res.message || '未知错误'))
              this.profileSizeList = []
              resolve() // 即使失败也继续执行
            }
          })
          .catch((err) => {
            console.error('获取型材尺寸信息异常:', err)
            this.profileSizeList = []
            resolve() // 即使失败也继续执行
          })
      })
    },

    // 关闭详情弹窗
    closeDetailInfoModal() {
      this.detailInfoVisible = false
      this.currentDetailRecord = null
      this.accessoriesList = []
      this.glassSizeList = []
      this.profileSizeList = []
    },

    // 加载型材清单和配件清单数据
    loadMaterialsAndAccessories() {
      if (!this.model || !this.model.id) {
        return
      }
      getOrderMaterialsAndAccessories(this.model.id)
        .then((res) => {
          if (res.success) {
            console.log('获取型材清单和配件清单成功，数据:', res.result)

            // 判断是否为长风优化软件类型
            if (this.model.optimizationSoftwareType !== 1) {
              // 长风类型
              // 对长风型材清单进行汇总处理
              const profileMaterialsMap = new Map()
              const originalProfileMaterials = res.result.profileMaterials || []

              // 遍历原始型材数据
              originalProfileMaterials.forEach((item) => {
                // 生成唯一键：型材编号_型材名称_颜色_长度_宽度_高度
                const key = `${item.profileCode}_${item.profileName}_${item.color}_${item.length}_${item.width || ''}_${
                  item.height || ''
                }`

                if (profileMaterialsMap.has(key)) {
                  // 如果已存在相同型材，则累加数量和重量
                  const existingItem = profileMaterialsMap.get(key)
                  existingItem.quantity += item.quantity || 1
                  existingItem.weight += item.weight || 0

                  // 保存原始ID列表，用于后续查询切割详情
                  if (!existingItem.originalIds) {
                    existingItem.originalIds = [existingItem.id]
                  }
                  existingItem.originalIds.push(item.id)
                } else {
                  // 如果不存在，则添加新条目
                  profileMaterialsMap.set(key, { ...item })
                }
              })

              // 转换回数组
              this.profileMaterials = Array.from(profileMaterialsMap.values())
              console.log('汇总后的长风型材清单:', this.profileMaterials)

              // 对长风配件清单进行汇总处理
              const accessoriesMap = new Map()
              const originalAccessories = res.result.accessories || []

              // 遍历原始配件数据
              originalAccessories.forEach((item) => {
                // 生成唯一键：配件编号_配件名称_规格
                const key = `${item.accessoryCode || ''}_${item.accessoryName || ''}_${item.specification || ''}`

                if (accessoriesMap.has(key)) {
                  // 如果已存在相同配件，则累加数量
                  const existingItem = accessoriesMap.get(key)
                  existingItem.quantity = (parseFloat(existingItem.quantity) || 0) + (parseFloat(item.quantity) || 0)
                } else {
                  // 如果不存在，则添加新条目
                  accessoriesMap.set(key, { ...item })
                }
              })

              // 转换回数组
              this.accessoryList = Array.from(accessoriesMap.values())
              console.log('汇总后的长风配件清单:', this.accessoryList)
            } else {
              // 新格尔类型，直接使用原始数据
              this.profileMaterials = res.result.profileMaterials || []
              this.accessoryList = res.result.accessories || []
            }
          } else {
            console.warn('未获取到型材清单和配件清单数据:', res)
            this.$message.warning('未获取到型材清单和配件清单数据')
          }
        })
        .catch((err) => {
          console.error('获取型材清单和配件清单出错', err)
          this.$message.error('获取型材清单和配件清单失败：' + (err.message || '未知错误'))
        })
    },

    // 显示切割方案详情
    showCutDetails(record) {
      this.currentProfileMaterial = record
      this.cutDetailsVisible = true
      this.loadCutDetails(record)
    },

    // 加载切割方案详情
    loadCutDetails(record) {
      if (!this.model || !this.model.id || !record || !record.profileCode) {
        return
      }

      this.detailsLoading = true
      this.cutDetails = []

      getCutDetails(this.model.id, record.profileCode)
        .then((res) => {
          if (res.success) {
            this.cutDetails = res.result || []
          } else {
            this.$message.error(res.message || '获取切割方案详情失败')
          }
        })
        .catch((err) => {
          console.error('获取切割方案详情出错', err)
          this.$message.error('获取切割方案详情失败')
        })
        .finally(() => {
          this.detailsLoading = false
        })
    },

    // 显示长风切割详情
    showCfCutDetails(record) {
      this.currentProfileMaterial = record
      this.cfCutDetailsVisible = true
      this.loadCfCutDetails(record)
    },

    // 加载长风切割详情
    loadCfCutDetails(record) {
      if (!this.model || !this.model.id || !record) {
        return
      }

      this.detailsLoading = true
      this.cfCutDetails = []

      // 获取需要查询的ID列表
      const profileIds = record.originalIds || [record.id]

      // 使用Promise.all并行查询所有ID的切割详情
      const promises = profileIds.map((profileId) => {
        return this.$http.get(`/oms/cfProfileCutDetail/getByProfileId?profileId=${profileId}`)
      })

      Promise.all(promises)
        .then((responses) => {
          // 合并所有响应结果
          let allCutDetails = []
          responses.forEach((res) => {
            if (res.success && res.result) {
              allCutDetails = allCutDetails.concat(res.result)
            }
          })

          // 格式化数据以适配表格
          this.cfCutDetails = allCutDetails.map((item, index) => {
            return {
              ...item,
              serialNo: index + 1,
              cutScheme: `左端角度: ${item.sxB}°/${item.sxC}°, 右端角度: ${item.dxB}°/${item.dxC}°`,
            }
          })

          if (this.cfCutDetails.length == 0) {
            this.$message.info('未找到切割详情数据')
          }
        })
        .catch((err) => {
          console.error('获取长风切割详情出错', err)
          this.$message.error('获取长风切割详情失败')
        })
        .finally(() => {
          this.detailsLoading = false
        })
    },

    // 新增的workDetails相关
    showWorkDetails(record) {
      this.currentCutDetail = record
      this.workDetailsVisible = true
      this.loadWorkDetails(record)
    },

    // 加载workDetails数据
    loadWorkDetails(record) {
      if (!record || !record.id) {
        this.$message.warning('无法获取加工方案，缺少ID信息')
        return
      }

      this.workDetailsLoading = true
      this.workDetails = []

      // 获取加工方案详情
      this.$http
        .get(`/oms/cfProfileWorkDetail/getByCutId?cutId=${record.id}`)
        .then((res) => {
          if (res.success) {
            this.workDetails = res.result || []

            // 格式化加工方案数据
            this.workDetails = this.workDetails.map((item, index) => {
              return {
                ...item,
                serialNo: index + 1,
                workScheme: `${item.workName || ''} - ${item.workType || ''}`,
                position: `X:${item.positionX || 0}, Y:${item.positionY || 0}, Z:${item.positionZ || 0}`,
              }
            })

            if (this.workDetails.length == 0) {
              this.$message.info('未找到加工方案数据')
            }
          } else {
            this.$message.error(res.message || '获取加工方案详情失败')
          }
        })
        .catch((err) => {
          console.error('获取加工方案详情出错', err)
          this.$message.error('获取加工方案详情失败')
        })
        .finally(() => {
          this.workDetailsLoading = false
        })
    },
  },
}
</script> 

<style scoped>
/* 组件特有样式 */
.drawing-thumbnail-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.drawing-thumbnail {
  width: 60px;
  height: 60px;
  object-fit: contain;
  border: 1px solid #d9d9d9;
  border-radius: 2px;
  background-color: #f5f5f5;
}

.file-icon {
  font-size: 36px;
  color: #1890ff;
}

.thumbnail-filename {
  width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  text-align: center;
  font-size: 12px;
  margin-top: 5px;
}

.drawing-preview-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  max-height: 600px;
  overflow: auto;
}

.drawing-preview-image {
  max-width: 100%;
  max-height: 600px;
}

.drawing-preview-iframe {
  width: 100%;
  height: 600px;
}

.drawing-preview-filename {
  text-align: center;
  margin-top: 10px;
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}
</style>

<style>
/* 表格样式优化 */
.ant-table-thead > tr > th {
  background-color: #f5f7fa !important;
  color: rgba(0, 0, 0, 0.85) !important;
  font-weight: 500 !important;
}

.ant-table-tbody > tr:hover > td {
  background-color: #e6f7ff !important;
}

.ant-card-head {
  border-bottom: 2px solid #1890ff !important;
  background-color: #fafafa !important;
}

.ant-card-head-title {
  font-weight: 600 !important;
  color: #1890ff !important;
}

.ant-descriptions-bordered .ant-descriptions-item-label {
  background-color: #fafafa !important;
  font-weight: 500 !important;
}

/* 切割方案详情样式 */
.cut-details-header {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.cut-details-header p {
  margin-bottom: 5px;
}
</style> 